package de.dhbw.karlsruhe.picsim.gui.editor;

import de.dhbw.karlsruhe.picsim.gui.util.GuiUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: May 2, 2010
 * Time: 11:34:46 AM
 */
public abstract class AbstractPicEditor<T> extends AbstractCellEditor implements TableCellEditor {
    private static final Log log = LogFactory.getLog(AbstractPicEditor.class);
    private final JTextField jTextField;


    protected AbstractPicEditor() {
        jTextField = new JTextField(10);
    }

    @Override
    public final Component getTableCellEditorComponent(
            final JTable table, final Object value, final boolean isSelected, final int row, final int column) {

        jTextField.setText(String.valueOf(parseObject((T) value)));
        return jTextField;
    }


    @Override
    @Nullable
    public final Object getCellEditorValue() {
        final String text = jTextField.getText();
        log.debug("user has entered:" + text);
        final Integer integer = GuiUtils.userInputToInt(text);
        return integer != null ? parseUserInput(integer) : null;
    }

    /**
     * @param value das Objekt, welches editiert werden soll
     * @return der der Wert, welches das Objekt aktuell hält
     */
    protected abstract int parseObject(T value);

    /**
     * @param result die Zahl die der Anwender eingegeben hat
     * @return das neue Objekt
     */

    @Nullable
    protected abstract Object parseUserInput(int result);


}
